package com.yc.backoffice.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Controller
@RequestMapping("upload")
public class UploadController {
    @RequestMapping("itemsPic")
    public void itemsPic(HttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartHttpServletRequest mulREquest= (MultipartHttpServletRequest) request;
        MultipartFile file1=mulREquest.getFile("itemspic1");
        String uploadFolder=request.getServletContext().getRealPath("/upload");
        File uploadFolderFile=new File(uploadFolder);
        if(!uploadFolderFile.exists()){
            uploadFolderFile.mkdirs();
        }
        String suffix=file1.getOriginalFilename().split("\\.")[1];
        String fileName= UUID.randomUUID().toString().replace("-","")+"."+suffix;
        String totalPath=uploadFolder+"\\"+fileName;
        FileCopyUtils.copy(file1.getInputStream(),new FileOutputStream(new File(totalPath)));

        String imgURL="http://localhost:8888/upload/" + fileName;
        String responseJson="{\"imgUrl\":\""+imgURL+"\"}";
        response.setHeader("content-type","text/json;charset=utf-8");
        response.getWriter().write(responseJson);


    }

}
